<?php

class GiftPasswordController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','admin1'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new GiftPassword;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['GiftPassword']))
		{
			$model->attributes=$_POST['GiftPassword'];
			
			$sql="select * from zy_gift_password where password='".$model->password."'";
			
			$rs = yii::app()->db->createCommand($sql)->queryAll();
			if($rs[0][password] == $model->password && $rs[0]['state'] == 1 && $model->service_number == ''){
				//密码已经存在,可以领取
				$this->redirect(array('create','state'=>6,'pass'=>$model->password));
			}
			if(!empty($rs)){
				$getSystemTime = getdate();	//获取当前系统时间
				/*领奖状态:0,未分配,未领奖,未过期 ,1,已经分配给用户，未领奖，未过期,2,已经分配给用户，未领奖，已过期,3,已经分配给客
户，已领奖4. 未分配,未领奖，已过期
				*/
				if(strtotime("-1 week") <strtotime($rs[0]['time']) ){
					//1,已经分配给用户，未领奖，未过期
					if($rs[0]['state'] == 1){//必须从,网站页面填写代码,使得state状态为1,发奖员才能发奖成功
						$model->state = 3;
					
					}elseif($rs[0]['state'] == 2){
						//2,已经分配给用户，未领奖，已过期
						$this->redirect(array('create','state'=>2));
						
					}elseif($rs[0]['state'] == 3){
						//3,已经分配给客户，已领奖
						$this->redirect(array('create','state'=>3));
					}
					
				}else{
					//4. 未分配,未领奖，已过期
					$expire_date=date('Y-m-d',strtotime("+7 day",strtotime($rs[0]['time'])));
					$this->redirect(array('create','state'=>4,'password_expire_date'=>$expire_date));
				}
			}else{
				$this->redirect(array('create','state'=>5,'pass'=>$model->password));
				//return '领奖密码不存在';
			}
			
			$upsql="update zy_gift_password set `service_number`='".$model->service_number."' ,`state` ='".$model->state."' where 

password='".$model->password."'";
			$rss = yii::app()->db->createCommand($upsql)->execute();
			//在做密码兑奖的时候,状态值必须为1
			if($rss){
				$upsqls="update zy_activity set `Used_gift_number` = Used_gift_number + 1 where activity_id='".$rs[0][activity_id]."'";
				yii::app()->db->createCommand($upsqls)->execute();
				$this->redirect(array('giftPassword/admin'));//return '领奖成功';
			}
			
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['GiftPassword']))
		{
			$model->attributes=$_POST['GiftPassword'];
			if($model->save())
				$this->redirect(array('admin','id'=>$model->gift_password_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('GiftPassword');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		/*$userId = yii::app()->user->userParentId();
		$sql="select * from zy_gift_password where state <> 3 and suser_id='".$userId."'";
		$rs = yii::app()->db->createCommand($sql)->queryAll();
		$getSystemTime = getdate();	//获取当前系统时间
		
			领奖状态:0,未分配,未领奖,未过期 ,1,已经分配给用户，未领奖，未过期,2,已经分配给用户，未领奖，已过期,3,已经分配给客户，已领奖4. 未分配,

未领奖，已过期
	
		for($i = 0; $i<count($rs); $i++){
			if($getSystemTime['0'] > strtotime($rs[$i]['time']) ){
				if($rs[$i]['state'] == 0){
					$upsqls="update zy_gift_password set `state` = 4 where gift_password_id='".$rs[$i]['gift_password_id']."' and state = 0";
				}elseif($rs[$i]['state'] == 1){
					$upsqls="update zy_gift_password set `state` = 2 where gift_password_id='".$rs[$i]['gift_password_id']."' and state = 1";
				}
				if(!empty($upsqls)){
					$rss = yii::app()->db->createCommand($upsqls)->execute();
				}
			}
			
		}*/
	 // echo "合作商进行高级搜索";
		//$state=yii::app()->request->getparam('state');
		
	    $model=new GiftPassword('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['GiftPassword']))
			$model->attributes=$_GET['GiftPassword'];
		$this->render('admin',array(
			'model'=>$model,
		));
	    
	}

	public  function actionAdmin1()
	{		
		
		$state=yii::app()->request->getparam('state');
		$model=new GiftPassword('search2');
		if($state[0]==1&&$state[1]==2&&$state[2]==3)
		   {
			// echo "列表栏";
				$model->attributes=$_GET['GiftPassword'];
				$model->state=$state;
			}
				$model->attributes=$_GET['GiftPassword'];
			
			
		$this->render('admin1',array(
				'model'=>$model,
		));
		
	}
	public  function actionAdmin2()
	{
		$model=new GiftPassword('search');
	//	$user_id=yii::app()->user->id;
	//	$model->user_id=$user_id;
	//	$modell->attributes=$_GET['GiftPassword'];
		//$sql='select b.* from zy_activity as a,zy_gift_password as b where a.activity_id=b.activity_id and a.user_id='.Yii::app()->user->id;
		//$rs=yii::app()->db-createCommand($sql)->queryAll();
		$this->render('admin2',array(
				'model'=>$model,
				
		));
	
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return GiftPassword the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=GiftPassword::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param GiftPassword $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='gift-password-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
